<?php
declare (strict_types = 1);

namespace app\model;

use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class Coin extends Model
{
    public static function generateCode() {
        $manager = Db::name('manager')->find(1);
        $mcode = $manager['code'] + 0;
        $arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T'];
        $sqlArr = [];
        $activeCode = '';
        for ($i = 0; $i < 501; $i ++) {
            $index = random_int(0,count($arr)-1);
            $code = $arr[$index].$mcode;
            $i == 0 ? $activeCode = $code : $activeCode.=("\r".$code);
            array_push($sqlArr,['code' => $code]);
            $mcode++;
        }
        (new Coin()) ->saveAll($sqlArr);
        Db::name('manager')->where('id',1)->update(['code' => $mcode]);
        return $activeCode;
    }

    public static function take($code,$uid) {
        $coin = self::where('code',$code)->find();
        if($coin) {
            $user = Db::name('user')->find($uid);
            $user['coin'] += 1;
            $user['gain_coin'] += 1;
            Db::name('user')->save($user);
           return self::where('code',$code) -> delete();
        }
        return $coin;
    }

    public static function addCoin($uid, $share) {
        $user = Db::name('user')->find($uid);
        $user['coin'] += 1;
        $user['gain_coin'] += 1;
        $user['share_date'] = $share;
        Db::name('user')->save($user);
    }
}
